/**
 * @Author: lianghuan
 * @Description: User
 * @emoji - ( ゜- ゜)つロ 乾杯~
 * @email lianghuanA@outlook.com
 * @Date: 2021-10-12 10:39
 * @Version: 1.0.0
 */

package controller

import (
	"github.com/gin-gonic/gin"
	"go-gin/common"
	"go-gin/model"
	"go-gin/response"
	"go-gin/util"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"net/http"
)

func Register(ctx *gin.Context) {
	DB := common.GetDB()

	request := model.User{}
	err := ctx.BindJSON(&request)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, err.Error())
		return
	}

	name := request.Name
	tel := request.Tel
	password := request.Password
	log.Println(name, tel, password)
	if len(tel) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位!")
		return
	}

	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位!")
		return
	}

	if len(name) == 0 {
		name = util.RandomString(10)
	}

	// 判断手机号是否存在
	if isTelephoneExist(DB, tel) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号已存在!")
		return
	}

	newPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "密码加密失败!")
		return
	}
	userEntity := model.User{
		Name:     name,
		Tel:      tel,
		Password: string(newPwd),
	}

	DB.Create(&userEntity)
	//返回结果
	response.Ok(ctx, nil, "注册成功")
}

func Login(ctx *gin.Context) {
	db := common.GetDB()
	//获取参数
	tel := ctx.PostForm("tel")
	password := ctx.PostForm("password")

	var user model.User
	db.Where("tel = ?", tel).First(&user)
	if user.ID == 0 {
		//用户不存在
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在!")
		return
	}
	// 判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "密码错误!")
		return
	}

	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "生成token失败")
		return
	}
	response.Ok(ctx, gin.H{"token": token}, "ok")

}

func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	res := db.Where("tel = ?", telephone).First(&user)
	if res.Error != nil {
		return false
	}
	return true
}
